package com.yuyou.tas.lesson.service.impl;

import com.yuyou.tas.lesson.mapper.LessonChapterMapper;
import com.yuyou.tas.lesson.mapper.LessonClassChapterMapper;
import com.yuyou.tas.lesson.service.*;
import com.yuyou.tas.lesson.service.comm.OfficeService;
import com.yuyou.tas.lesson.service.comm.Subj7SectLimitService;
import com.yuyou.tas.service.api.admin.service.CommJobAPI;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterDetDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterPageDTO;
import com.yuyou.tas.service.api.lesson.entity.BaseChapter;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.lesson.entity.LessonChapter;
import com.yuyou.tas.service.api.lesson.entity.LessonClassChapter;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.admin.CommJobEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.message.CommMess;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.LoginRedisUtil;
import com.yuyou.tas.util.tool.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class LessonChapterServiceImpl implements ILessonChapterService{

	@Autowired
	private LessonChapterMapper lessonChapterMapper;
	
	@Autowired
	private IBaseChapterService baseChapterService;
	
	@Autowired
	private ILessonService lessonService;
	
	/*@Autowired
	private OrganLimitService organLimitService;*/
	
	@Autowired
	private Subj7SectLimitService subj7SectLimitService;
	
	@Autowired
	private ILessonClassService lessonClassService;
	
	@Autowired
	private OfficeService officeService;

	@Autowired
	private LessonClassChapterMapper lessonClassChapterMapper;
	@Autowired
	private ILessonClassChapterService lessonClassChapterService;
	
    @Autowired
    private ILessonResourceService lessonResourceService;
	
	@Autowired
    private CommJobAPI commJobAPI;
    
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		return lessonChapterMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(LessonChapter record) {
		record.setCreateTime(new Date());
		record.setId(Sequence.getSequence().nextId());			
		return lessonChapterMapper.insert(record);
	}

	@Override
	public LessonChapter selectByPrimaryKey(Long id) {
		return lessonChapterMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public LessonChapter selectByPKandOrgan(Long id, Long authOrganizationId) {
		return lessonChapterMapper.selectByPKandOrgan(id, authOrganizationId);
	}
	
	@Override
	public int updateByPrimaryKeySelective(LessonChapter record) {
		return lessonChapterMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int findLessonChapterCount(Pagination<LessonChapterPageDTO> queryPgn) {
		return lessonChapterMapper.findLessonChapterCount(queryPgn);
	}

	@Override
	public List<LessonChapterPageDTO> findLessonChapterPageList(
			Pagination<LessonChapterPageDTO> queryPgn) {
		return lessonChapterMapper.findLessonChapterPageList(queryPgn);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> addLessonChapters(List<Long> baseChapterIds,Long lessonId ,Boolean isSystem,Long userId,Long sortId) throws Exception{
		
		checkDoubleCha(baseChapterIds,lessonId);
		lessonService.validate(true,lessonId,Collections.emptyList(),baseChapterIds,userId);
		lessonService.checkPublicLesson(lessonId);
		LoginRedisObj obj=LoginRedisUtil.getUserObj(userId);				
		Integer maxSort=null;
		if(sortId!=null){
			LessonChapter sortObj=this.selectByPrimaryKey(sortId);
			maxSort=sortObj.getSort();
		}else{
			maxSort=lessonChapterMapper.selectMaxSort(lessonId);
		}
				
		List<LessonChapter> sortList=lessonChapterMapper.findByLessonId7Sort(lessonId,maxSort);	
				
		for(Long baseChapterId:baseChapterIds){
			maxSort=maxSort+1;
			//讲次库不分机构
			BaseChapter baseChapter=baseChapterService.selectByPrimaryKey(baseChapterId);				
			LessonChapter lc=new LessonChapter();
			lc.setpId(null);
			lc.setAuthOrganizationId(obj.getOrganizationId());
			lc.setIsStan(isSystem?1:0);
			lc.setLessonId(lessonId);
			lc.setSort(maxSort);	
			lc.setIsHide(0);
			lc.setBaseChapterId(baseChapter.getId());
			lc.setCreateUser(userId);
			lc.setStatus(LessonEnums.status.init.getValue());
			this.insert(lc);
		}	
		sort(sortList,maxSort);
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Transactional(rollbackFor=Exception.class,timeout=60)
	public void checkDoubleCha(List<Long> baseChapterIds,Long lessonId) throws Exception{
		//重复讲次教研
		List<LessonChapter> lcList=this.findLessonChapterByLessId(lessonId);
		String res=lcList.stream().filter(item->baseChapterIds.contains(item.getBaseChapterId())).map(m -> {
			BaseChapter baseChapter=baseChapterService.selectByPrimaryKey(m.getBaseChapterId());	
			return baseChapter.getName();}).collect(Collectors.joining(","));
		long c=lcList.stream().filter(item->baseChapterIds.contains(item.getBaseChapterId())).count();
		if(c>0){
			throw new BusinessException("你选择的讲次【"+res+"】已经存在");
		}
	}
	
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public void sort(List<LessonChapter> sortList,Integer maxSort){
		for(LessonChapter sort:sortList){
			maxSort=maxSort+1;
			LessonChapter lessonChapter=new LessonChapter();
			lessonChapter.setId(sort.getId());
			lessonChapter.setSort(maxSort);
			lessonChapterMapper.updateByPrimaryKeySelective(lessonChapter);
		}
	}
	
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> delLessonChapters(Long lessonId,Long chapterId,Long userId) throws Exception{	
		lessonService.validate(true,lessonId,Arrays.asList(chapterId),Collections.emptyList(),userId);
		lessonService.checkPublicLesson(lessonId);
		Integer maxSort=this.selectByPrimaryKey(chapterId).getSort();
		List<LessonChapter> sortList=lessonChapterMapper.findByLessonId7Sort(lessonId,maxSort);
		sort(sortList,maxSort-1);		
		lessonChapterMapper.deleteByPrimaryKey(chapterId);	
		return ResBoolSimpleInfo.getSuccessInfo();
	}



	
	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> sortAllLesCha(Long lessonId,List<Long> ids ,Long userId)throws Exception {
		lessonService.validate(true,lessonId,ids,Collections.emptyList(),userId);
		lessonService.checkPublicLesson(lessonId);
		List<LessonChapter> lcList=this.findLessonChapterByLessId(lessonId);
		if(lcList.size()!=ids.size()){
			throw new BusinessException("讲次数量不一致");
		}		
		int sort=0;
		for(Long id:ids){
			sort++;
			LessonChapter lessonChapter=new LessonChapter();
			lessonChapter.setId(id);
			lessonChapter.setSort(sort);
			lessonChapterMapper.updateByPrimaryKeySelective(lessonChapter);
		}
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> changeLessonChapters(Long lessonId,Long id,Long baseChapterId,Long userId)throws Exception {
		checkDoubleCha(Stream.of(baseChapterId).collect(Collectors.toList()),lessonId);
		lessonService.validate(true,lessonId,Arrays.asList(id),Arrays.asList(baseChapterId),userId);
		lessonService.checkPublicLesson(lessonId);
		LessonChapter lessonChapter=lessonChapterMapper.selectByPrimaryKey(id);
		BaseChapter baseChapter=baseChapterService.selectByPrimaryKey(baseChapterId);	
		lessonChapter.setBaseChapterId(baseChapter.getId());	
		this.updateByPrimaryKeySelective(lessonChapter);
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	@Override
	public ResBoolSimpleInfo<LessonChapterDetDTO> detailLesChapters(Long lessonId,Long id,Long userId)throws Exception {
		LoginRedisObj obj=LoginRedisUtil.getUserObj(userId);
		
		Lesson lesson=lessonService.selectByPrimaryKey(lessonId);
		LessonChapter lessonChapter=lessonChapterMapper.selectByPrimaryKey(id);	
		BaseChapter baseChapter=baseChapterService.selectByPrimaryKey(lessonChapter.getBaseChapterId());	

		//只能引用本机构或者标准的课程
		if(lesson.getIsStan().equals(0) && !lesson.getAuthOrganizationId().equals(obj.getOrganizationId())){
			throw new BusinessException(CommMess.ERR_POWER);
		}
		if(lessonChapter.getIsStan().equals(0) && !lessonChapter.getAuthOrganizationId().equals(obj.getOrganizationId())){
			throw new BusinessException(CommMess.ERR_POWER);
		}
		subj7SectLimitService.checkByUserId(userId, lesson.getDataSubject(), lesson.getBaseSectionId());
		subj7SectLimitService.checkByUserId(userId, baseChapter.getDataSubject(), baseChapter.getBaseSectionId());			
				
		ResBoolSimpleInfo<LessonChapterDetDTO> res=new ResBoolSimpleInfo<LessonChapterDetDTO>();
		LessonChapterDetDTO dto=new LessonChapterDetDTO();	
		DefindBeanUtils.copyProperties(lessonChapter, dto);		
		dto.setName(baseChapter.getName());
		dto.setCourseUrl(baseChapter.getCourseUrl());;
		dto.setCourseName(baseChapter.getCourseName());;
		dto.setCourseSize(baseChapter.getCourseSize());	
		dto.setLectureUrl(baseChapter.getLectureUrl());
		dto.setLectureName(baseChapter.getLectureName());
		dto.setLectureSize(baseChapter.getLectureSize());		
		dto.setDataSubject(baseChapter.getDataSubject());
		dto.setBaseLevelId(baseChapter.getBaseLevelId());
		dto.setBaseSectionId(baseChapter.getBaseSectionId());
		dto.setBaseTrimesterId(baseChapter.getBaseTrimesterId());
		dto.setChapterType(baseChapter.getChapterType());
		dto.setType(baseChapter.getType());
		dto.setLectureId(baseChapter.getLectureId());
		res.setSuccess(true);
		res.setData(dto);
		return res;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	@Deprecated
	public ResBoolSimpleInfo<String> hideLesChapters(Long lessonId, Long id,Integer isHide,Long userId) throws Exception {
		lessonService.validate(true,lessonId,Arrays.asList(id),Collections.emptyList(),userId);
		lessonService.checkPublicLesson(lessonId);
		LessonChapter lc=this.selectByPrimaryKey(id);
		if(lc.getIsHide()==isHide){
			return ResBoolSimpleInfo.getSuccessInfo();
		}
		
		if(isHide==1){
			LessonChapter lessonChapter=new LessonChapter();
			lessonChapter.setId(id);
			lessonChapter.setIsHide(isHide);
			this.updateByPrimaryKeySelective(lessonChapter);
			
			Integer maxSort=this.selectByPrimaryKey(id).getSort();
			List<LessonChapter> sortList=lessonChapterMapper.findByLessonId7Sort(lessonId,maxSort);
			sort(sortList,maxSort-1);
		}else{
			LessonChapter lessonChapter=new LessonChapter();
			lessonChapter.setId(id);
			lessonChapter.setIsHide(isHide);
		
			Integer maxSort=this.selectByPrimaryKey(id).getSort();
			List<LessonChapter> sortList=lessonChapterMapper.findByLessonId7Sort(lessonId,maxSort-1);
			sort(sortList,maxSort);
			
			this.updateByPrimaryKeySelective(lessonChapter);
		}

		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public List<LessonChapter> findLessonChapterByLessId(Long lessonId) {
		return lessonChapterMapper.findLessonChapterByLessId(lessonId);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> copyChapterByChapter(Long lessonPId,
			Lesson currLesson,LoginRedisObj obj) throws Exception {
		List<LessonChapter> list = this.findLessonChapterByLessId(lessonPId);				
		for(LessonChapter lc:list){
			LessonChapter newLc=new LessonChapter();
			DefindBeanUtils.copyProperties(lc, newLc);	
			newLc.setLessonId(currLesson.getId());
			newLc.setIsStan(obj.getIsSystem()?1:0);
			newLc.setpId(obj.getIsSystem()?null:lc.getId());
			newLc.setAuthOrganizationId(obj.getOrganizationId());
			newLc.setStatus(LessonEnums.status.init.getValue());
			newLc.setCreateUser(obj.getUserId());
			this.insert(newLc);
		}
		return ResBoolSimpleInfo.getSuccessInfo();
		
	}


	@Override
	public ResBoolSimpleInfo<LessonClassChapter> detailLessonClassChapter(Long lessonClassId, Long lessonId, Long lessonChapterId) {
		LessonClassChapter lessonClassChapter = lessonClassChapterMapper.selectByLessonIdClassIdChapterId(lessonClassId, lessonId, lessonChapterId);

		ResBoolSimpleInfo<LessonClassChapter> res = new ResBoolSimpleInfo<LessonClassChapter>();
		res.setSuccess(true);
		res.setData(lessonClassChapter);
		return res;
	}

	@Override
	public List<String> findBaseChaInLesson(Long baseChapterId) {
		return lessonChapterMapper.findBaseChaInLesson(baseChapterId);
	}

	@Override
	public Integer findCountByBaseCha(Long baseChapterId) {
		return lessonChapterMapper.findCountByBaseCha(baseChapterId);
	}

	@Override
	public void delByless(Long lessonId) {
		lessonChapterMapper.delByless(lessonId);
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResBoolSimpleInfo<String> publishLesChapters(Long lessonId, List<Long> ids,Long userId) throws Exception {
		
		//校验
		for(Long id:ids){
			lessonService.validate(true,lessonId,Arrays.asList(id),Collections.emptyList(),userId);
			LessonChapter lc=this.selectByPrimaryKey(id);
			if(lc.getStatus().equals(LessonEnums.status.pass.getValue())||lc.getStatus().equals(LessonEnums.status.passing.getValue())){
				throw new BusinessException("不能重复发布");
			}
		}
		
		for(Long id:ids){
			//同步发布的讲次到引用该班级的讲次
			upGradeClassByLessonCha(id);		
		}			
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResBoolSimpleInfo<String> upGradeClassByLessonCha(Long lessonChapId) throws Exception{

		LessonChapter lessonChapter=new LessonChapter();
		lessonChapter.setId(lessonChapId);
		lessonChapter.setStatus(LessonEnums.status.pass.getValue());
		this.updateByPrimaryKeySelective(lessonChapter);
			
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
//	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> delOldData() {
		List<LessonClassChapter> list = lessonClassChapterMapper.findOldData();
		list.forEach(lessonClassChapter -> {
			//置空ppt和讲义url
			lessonClassChapterMapper.updateUrl2empty(lessonClassChapter.getId());
			commJobAPI.addResourceJob(lessonClassChapter.getCourseUrl(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
			commJobAPI.addResourceJob(lessonClassChapter.getLectureUrl(), CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
		});
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public ResBoolSimpleInfo<String> delOldDataLeave() {
		List<String> list = lessonResourceService.findOldDataLeave();
		list.forEach(resourceId -> {
			//在baseChapter和lessonClassChapter没有被用到
			if(baseChapterService.findByResourceId(resourceId) < 1 && lessonClassChapterMapper.findByResourceId(resourceId) < 1){
				commJobAPI.addResourceJob(resourceId, CommJobEnums.type.resource.getValue(), CommJobEnums.tag.resource.getValue());
			}
		});
		return ResBoolSimpleInfo.getSuccessInfo();
	}


}
